Page({
  data: {
    routeInfo: {
      name: 'home',
      meta: {
        title: '校园新闻网',
        level: 1
      }
    },
    slides: [],
    quickNavItems: [
      { id: 1, title: '学校简介', icon: '/static/icons/college.png', action: '/pages/search/search' },
      { id: 2, title: '学校荣誉', icon: '/static/icons/honor.png', action: '/pages/search/search' },
      { id: 3, title: '学校组织', icon: '/static/icons/organization.png', action: '/pages/search/search' },
      { id: 4, title: '教务中心', icon: '/static/icons/teaching.png', action: '/pages/education/education' },
      { id: 5, title: '更多详情', icon: '/static/icons/more.png', action: '/pages/search/search' },
      { id: 6, title: '党群组织', icon: '/static/icons/party.png', action: '/pages/search/search' }
    ],
    hotNews: [],
    loading: false
  },

  onLoad() {
    this.fetchHomeSlides()
    this.fetchHotNews()
  },

  // 获取轮播图数据
  fetchHomeSlides() {
    // 模拟轮播图数据，使用云端图片URL
    const mockSlides = [
      {
        id: 1,
        title: '轮播图1',
        image: '/public/images/HomeSlide/Slide1.jpg'
      },
      {
        id: 2, 
        title: '轮播图2',
        image: '/public/images/HomeSlide/Slide2.jpg' 
      },
      {
        id: 3,
        title: '轮播图3',
        image: '/public/images/HomeSlide/Slide3.jpg'
      }
    ]
    this.setData({ slides: mockSlides })
  },

  // 获取热门新闻
  fetchHotNews() {
    this.setData({ loading: true })
    const { articleApi } = require('../../utils/api')
    
    // 从ID 97623开始获取4篇新闻
    Promise.all([
      articleApi.getArticleDetail(97623),
      articleApi.getArticleDetail(97624),
      articleApi.getArticleDetail(97625),
      articleApi.getArticleDetail(97626)
    ])
    .then(responses => {
      console.log('API响应详情:', responses)
      const hotNews = responses.map(res => {
        const data = res.data || res || {}
        console.log('单篇文章数据:', data)
        return {
          id: String(data.news_id || data.newsId || data.id || ''),
          title: data.title || '无标题',
          contentPreview: data.contentText || data.content || '',
          pubTime: data.pubTime || new Date().toISOString()
        }
      })
      console.log('处理后新闻数据:', hotNews)
      this.setData({
        hotNews,
        loading: false
      })
    })
    .catch(err => {
      console.error('获取热门新闻失败:', err)
      this.setData({ loading: false })
      wx.showToast({
        title: '获取新闻失败',
        icon: 'none'
      })
    })
  },

  // 格式化时间
  formatTime(dateString) {
    if (!dateString) return ''
    const date = new Date(dateString)
    const now = Date.now()
    const diff = now - date.getTime()
    const minute = 60 * 1000
    const hour = 60 * minute
    const day = 24 * hour

    if (diff < minute) return '刚刚'
    if (diff < hour) return `${Math.floor(diff / minute)}分钟前`
    if (diff < day) return `${Math.floor(diff / hour)}小时前`
    if (diff < 7 * day) return `${Math.floor(diff / day)}天前`
    
    return date.toLocaleDateString('zh-CN', {
      month: 'numeric',
      day: 'numeric'
    })
  },

  // 处理快捷导航点击
  handleQuickNav(e) {
    const item = e.currentTarget.dataset.item
    if (item.action === '/pages/education/education') {
      wx.navigateTo({ url: item.action })
    } else {
      wx.showToast({
        title: `点击了${item.title}`,
        icon: 'none'
      })
    }
  },

  // 跳转到新闻列表
  goToNews() {
    wx.navigateTo({ url: '/pages/news/list' })
  },

  // 跳转到新闻详情
  goToDetail(e) {
    try {
      const index = e.currentTarget.dataset.index
      if (!this.data.hotNews || index >= this.data.hotNews.length) {
        throw new Error('新闻数据未加载或索引越界')
      }
      
      const newsItem = this.data.hotNews[index]
      const newsId = newsItem?.id || ''
      
      console.log('跳转详情参数:', {index, id: newsId, item: newsItem})
      
      if (!newsId) {
        wx.showToast({
          title: '正在加载文章数据...',
          icon: 'none',
          duration: 1500
        })
        return
      }
      
      wx.navigateTo({ 
        url: `/pages/news/detail?id=${newsId}`,
        fail: (err) => {
          console.error('跳转失败:', err)
          wx.showToast({
            title: '跳转详情页失败，请稍后再试',
            icon: 'none'
          })
        }
      })
    } catch (err) {
      console.error('跳转异常:', err)
      wx.showToast({
        title: '系统繁忙，请稍后再试',
        icon: 'none'
      })
    }
  }
})
